//SessionServlet.java
package com.ylaihui.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionServlet extends BaseServlet{
    protected void createSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取session， 有则获取对象，没有则创建session对象
        HttpSession session = req.getSession();

        //获取session 的 ID
        String id = session.getId();

        //session是否是最新的
        boolean isN = session.isNew();

        resp.getWriter().write("session id:" + id + ", session is new : " + isN);
    }

    protected void setKeyValue(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().setAttribute("username", "ylaihui");
        resp.getWriter().write("set session username, value is ylaihui");
    }

    protected void getKeyValue(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object username = req.getSession().getAttribute("username");

        resp.getWriter().write("username:" + username);
    }

    protected void getDefaultTimeout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取session的默认超时时间
        int maxInactiveInterval = req.getSession().getMaxInactiveInterval();

        resp.getWriter().write("session timeout:" + maxInactiveInterval + "s");
    }

    protected void lifeTimeout3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置session 3s超时
        req.getSession().setMaxInactiveInterval(3);
        resp.getWriter().write("session timeout:3s");
    }

    protected void deleteSessionNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置session立刻失效
        req.getSession().invalidate();
        resp.getWriter().write("session invalidate now");
    }

}
